package xjh.him.netty.codec;

import java.util.Objects;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import xjh.him.netty.Constant;

/**
 * 消息编码器
 */
public class MsgEncoder extends MessageToByteEncoder<Packet> {
    @Override
    protected void encode(ChannelHandlerContext ctx, Packet packet, ByteBuf byteBuf) throws Exception {
        Objects.requireNonNull(packet, "msg str cannot be null.");
        encode(packet, byteBuf);
    }

    public void encode(Packet packet, ByteBuf out) {
        byte[] bs = packet.getData().getBytes();
        out.writeByte(Constant.MAGIC_NUM);
        out.writeByte(packet.getCommand());
        out.writeInt(bs.length);
        out.writeBytes(bs);
    }
}
